package com.estate.gateway.filter;

import com.alibaba.fastjson.JSONArray;
import com.estate.config.JwtConfig;
import com.estate.util.JsonResult;
import com.estate.util.ResultTool;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class CheckIsLoginGlobalFilter implements GlobalFilter, Ordered {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 校验用户是否登录
        log.info("校验用户是否登录");
        // 用户是否访问登录接口
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("访问的请求是:{}", path);
        if (path.contains("auth/login")) {
            // 放行
            return chain.filter(exchange);
        }
        // 用户是否携带token
        List<String> tokens = request.getHeaders().get("token");
        log.info("tokens:{}",tokens);
        if (tokens == null || tokens.size() == 0) {
            // 失败
            return error(exchange);
        }
        String token = tokens.get(0);
        log.info("token:{}",token);
        boolean b = JwtConfig.checkToken(token);
        log.info("b:{}",b);
        if (!b) {
            return error(exchange);
        }
        String id = JwtConfig.parseJWT(token).get("id").toString();
        String redisToken = stringRedisTemplate.opsForValue().get("token:fcy" + id);
        log.info("redisToken:{}",redisToken);
        if (!Objects.equals(redisToken, token)) {
            return error(exchange);
        }

        return chain.filter(exchange);
    }


    /**
     * token校验失败
     *
     * @param exchange
     * @return
     */
    private Mono<Void> error(ServerWebExchange exchange) {
        // 浏览器没有携带token
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        // 设置响应状态码
        response.setStatusCode(HttpStatus.resolve(403));
        // 设置返回格式
        response.getHeaders().set("ContentType", "application/json;charset=utf-8");
        // 设置返回的内容
        JsonResult result = ResultTool.fail(403, "用户没有登陆");
        String str = JSONArray.toJSONString(result);
        DataBuffer data = response.bufferFactory().wrap(str.getBytes(StandardCharsets.UTF_8));
        log.info("⽤户未携带token,{}", str);
        return response.writeWith(Mono.just(data));

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
